package src.D_WinSock;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

// 多线程实现在线咨询
public class D04_UDP_LeLe_Chat implements Runnable{
    DatagramSocket socket = null;
    BufferedReader br = null;
    private int iPort;
    private String toIP;
    private int toPort;

    public D04_UDP_LeLe_Chat(int iPort, String toIP, int toPort) {
        this.iPort = iPort;
        this.toIP = toIP;
        this.toPort = toPort;
        try {
            // 1、创建一个Socket
            socket = new DatagramSocket(iPort);
            // 2、建包打包
            br = new BufferedReader(new InputStreamReader(System.in)); // 接收控制台内容放到io里
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        try {
            while (true){    // 循坏发送信息
                String msg = br.readLine();  // 这里有bug，会多读取一个\n进去，所以mengmeng那边隔一条消息收不到
                byte[] msgs = msg.getBytes();
                DatagramPacket packet = new DatagramPacket(
                        msgs,                                                    // 数据，并转化为字节数组
                        0,                                                      // 数据起始下标
                        msgs.length,                                           // 结束下标
                        new InetSocketAddress(this.toIP,this.toPort) // ip 和 端口
                );
                // 3、发送包
                socket.send(packet);
                if (br.readLine().equals("close")) break; // 结束聊天
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 4、关流
            try {
                if (br != null){
                    br.close();
                }
                if (socket != null){
                    socket.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

class Test01{
    public static void main(String[] args) {
        new Thread(new D04_UDP_LeLe_Chat(8888,"localhost",9999)).start();
        new Thread(new D04_UDP_MengMemg_Chat(7777,"小猪梦梦")).start();
    }
}
